#include "GamePlayLayer.h"
#include "ResourceManager.h"
#include "Road.h"
#include "Car.h"
#include "Moto.h"
#include "Bus.h"
#include "CEMoveBySpeed.h"
#include "GameManager.h"
#include "InputScene.h"
#include "VehicleInfo.h"
#include "HNAlertView.h"
#include "InputField.h"

#define BUTTON_TOP_PADDING 30
#define PADDING_SCROLL 100

GamePlayLayer::GamePlayLayer()
{
}

bool GamePlayLayer::init(){
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	setContentSize(visibleSize);
	road = 0;
	GameManager::getInstance()->gamePlayLayer = this;
    CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(GamePlayLayer::gameTimeChangeNotification), kGameTimeIncreaseNotification, 0);
	isShowingAlert = false;

	if(GameManager::getInstance()->isUseable){
		setTouchEnabled(true);
		scheduleUpdate();
		//setScale(0.4f);

		road = 0;

		addControls();

		if(TRIAL_MODE){
			CCLabelTTF* trialLabel = CCLabelTTF::create("Demo", "", 100, CCSizeMake(400, 200), kCCTextAlignmentCenter, kCCVerticalTextAlignmentCenter);
			trialLabel->setPosition(ccp(visibleSize.width/2, visibleSize.height/2));
			addChild(trialLabel, 1);
		}
	}
	else{
		CCLabelTTF* trialLabel = CCLabelTTF::create("Demo !", "", 100, CCSizeMake(400, 200), kCCTextAlignmentCenter, kCCVerticalTextAlignmentCenter);
		trialLabel->setPosition(ccp(visibleSize.width/2, visibleSize.height/2));
		addChild(trialLabel);
	}

	return true;
}

void GamePlayLayer::onEnter(){
	CCLayer::onEnter();

	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,2,true);
}
GamePlayLayer::~GamePlayLayer()
{
    if(road) {
		road->release();
    }
    CCNotificationCenter::sharedNotificationCenter()->removeAllObservers(this);
}

bool GamePlayLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent){
	currentTouchPoint = pTouch->getLocation();
	if(road)
		road->stopAllActions();
	return true;
}

void GamePlayLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent){
	CCPoint touchPoint = pTouch->getLocation();
	
	if(road){
		float deltaX = touchPoint.x - currentTouchPoint.x;
		CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
		float newPos = road->getPositionX() + deltaX*2;

		if(newPos < PADDING_SCROLL && newPos > - road->getContentSize().width + visibleSize.width - PADDING_SCROLL){
			road->setPositionX(newPos);
		}
	}

	currentTouchPoint = touchPoint;
}

void GamePlayLayer::scrollRight(CCObject *sender, CCControlEvent controlEvent){
	CEMoveBySpeed* moveRoadAction = CEMoveBySpeed::create(200, ccp(-100000, 0));
	moveRoadAction->setTag(0);
	road->runAction(moveRoadAction);
}

void GamePlayLayer::scrollLeft(CCObject *sender, CCControlEvent controlEvent){
	CEMoveBySpeed* moveRoadAction = CEMoveBySpeed::create(200, ccp(100000, 0));
	moveRoadAction->setTag(0);
	road->runAction(moveRoadAction);
}

void GamePlayLayer::scrollToBegin(CCObject *sender, CCControlEvent controlEvent){
	road->stopAllActions();
	CCMoveTo* moveToBeginAction = CCMoveTo::create(1.0f, ccp(PADDING_SCROLL, road->getPositionY()));
	road->runAction(moveToBeginAction);
}

void GamePlayLayer::scrollToEnd(CCObject *sender, CCControlEvent controlEvent){
	road->stopAllActions();
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCMoveTo* moveToBeginAction = CCMoveTo::create(1.0f, ccp(- road->getContentSize().width + visibleSize.width - PADDING_SCROLL, road->getPositionY()));
	road->runAction(moveToBeginAction);
}

void GamePlayLayer::update(float delta){
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

	if(road){
		if(road->getPositionX() > PADDING_SCROLL || road->getPositionX() < - road->getContentSize().width + visibleSize.width - PADDING_SCROLL){
			road->stopAllActions();
		}

		char numVerhicleString[64];
		sprintf(numVerhicleString, "Number vehicles: %d", road->getVehicles()->count());
		numVerhicleLabel->setString(numVerhicleString);

//		gameTimer->update(delta);
	}

}

void GamePlayLayer::addControls(){

	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	int xOffset = 50;
	int buttonY = visibleSize.height - BUTTON_TOP_PADDING;

	CCScale9Sprite* scrollToBeginSprite = CCScale9Sprite::createWithSpriteFrameName("ScrollEndIcon.png");
	scrollToBeginSprite->setCapInsets(CCRectMake(0, 0, scrollToBeginSprite->getContentSize().width, scrollToBeginSprite->getContentSize().height));
	scrollToBeginSprite->setScaleX(-1);
	CCControlButton *scrollToBeginButton = CCControlButton::create(scrollToBeginSprite);
	scrollToBeginButton->setPreferredSize(CCSizeMake(40, 40));
	scrollToBeginButton->setPosition(CCPointMake(xOffset, buttonY));
	scrollToBeginButton->addTargetWithActionForControlEvents(this, cccontrol_selector(GamePlayLayer::scrollToBegin), CCControlEventTouchUpInside);
	addChild(scrollToBeginButton, 1);
	xOffset += 50;

	CCScale9Sprite* scrollLeftSprite = CCScale9Sprite::createWithSpriteFrameName("ScrollRightIcon.png");
	scrollLeftSprite->setCapInsets(CCRectMake(0, 0, scrollLeftSprite->getContentSize().width, scrollLeftSprite->getContentSize().height));
	scrollLeftSprite->setScaleX(-1);
	CCControlButton *scrollLeftButton = CCControlButton::create(scrollLeftSprite);
	scrollLeftButton->setPreferredSize(CCSizeMake(40, 40));
	scrollLeftButton->setPosition(CCPointMake(xOffset, buttonY));
	scrollLeftButton->addTargetWithActionForControlEvents(this, cccontrol_selector(GamePlayLayer::scrollLeft), CCControlEventTouchUpInside);
	addChild(scrollLeftButton, 1);
	xOffset += 50;

	CCScale9Sprite* scrollRightSprite = CCScale9Sprite::createWithSpriteFrameName("ScrollRightIcon.png");
	scrollRightSprite->setCapInsets(CCRectMake(0, 0, scrollRightSprite->getContentSize().width, scrollRightSprite->getContentSize().height));
	CCControlButton *scrollRightButton = CCControlButton::create(scrollRightSprite);
	scrollRightButton->setPreferredSize(CCSizeMake(40, 40));
	scrollRightButton->setPosition(CCPointMake(xOffset, buttonY));
	scrollRightButton->addTargetWithActionForControlEvents(this, cccontrol_selector(GamePlayLayer::scrollRight), CCControlEventTouchUpInside);
	addChild(scrollRightButton, 1);
	xOffset += 50;

	CCScale9Sprite* scrollToEndSprite = CCScale9Sprite::createWithSpriteFrameName("ScrollEndIcon.png");
	scrollToEndSprite->setCapInsets(CCRectMake(0, 0, scrollToEndSprite->getContentSize().width, scrollToEndSprite->getContentSize().height));
	CCControlButton *scrollToEndButton = CCControlButton::create(scrollToEndSprite);
	scrollToEndButton->setPreferredSize(CCSizeMake(40, 40));
	scrollToEndButton->setPosition(CCPointMake(xOffset, buttonY));
	scrollToEndButton->addTargetWithActionForControlEvents(this, cccontrol_selector(GamePlayLayer::scrollToEnd), CCControlEventTouchUpInside);
	addChild(scrollToEndButton, 1);
	xOffset += 50;

	xOffset += 50;
	CCScale9Sprite* replaySprite = CCScale9Sprite::createWithSpriteFrameName("ReplayIcon.png");
	replaySprite->setCapInsets(CCRectMake(0, 0, replaySprite->getContentSize().width, replaySprite->getContentSize().height));
	CCControlButton *replayButton = CCControlButton::create(replaySprite);
	replayButton->setPreferredSize(CCSizeMake(40, 40));
	replayButton->setPosition(CCPointMake(xOffset, buttonY));
	replayButton->addTargetWithActionForControlEvents(this, cccontrol_selector(GamePlayLayer::replayButtonTouched), CCControlEventTouchUpInside);
	addChild(replayButton, 1);
	xOffset += 50;

	CCScale9Sprite* settingSprite = CCScale9Sprite::createWithSpriteFrameName("SettingIcon.png");
	settingSprite->setCapInsets(CCRectMake(0, 0, settingSprite->getContentSize().width, settingSprite->getContentSize().height));
	CCControlButton *settingButton = CCControlButton::create(settingSprite);
	settingButton->setPreferredSize(CCSizeMake(40, 40));
	settingButton->setPosition(CCPointMake(visibleSize.width - 50, buttonY));
	settingButton->addTargetWithActionForControlEvents(this, cccontrol_selector(GamePlayLayer::settingButtonTouched), CCControlEventTouchUpInside);
	addChild(settingButton, 1);

//    float inputFieldWidth = 200;
//	sessionTimeInputField = new InputField();
//	sessionTimeInputField->init(CCRectMake(430, buttonY, inputFieldWidth, 40), "Session time", 20, 100);
//	sessionTimeInputField->editBox->setText("0");
//	addChild(sessionTimeInputField);
    
    timeLabel = CCLabelTTF::create("", "", 20);
	timeLabel->setPosition(ccp(430, buttonY));
    updateTimeLabel();
	addChild(timeLabel);
    
    endTimeLabel = CCLabelTTF::create("", "", 20);
    endTimeLabel->setPosition(ccp(600, buttonY));
    updateEndTimeLabel();
    addChild(endTimeLabel);
    
    numVerhicleLabel = CCLabelTTF::create("Number vehicles: 0", "", 20);
	numVerhicleLabel->setPosition(ccp(810, buttonY));
	addChild(numVerhicleLabel);

//	gameTimer = new CCTimer;
//	gameTimer->initWithTarget(this, schedule_selector(GamePlayLayer::oneSecondTick), 1, 0, 0);
}

void GamePlayLayer::settingButtonTouched(CCObject *sender, CCControlEvent controlEvent){
	CCDirector::sharedDirector()->pushScene(CCTransitionSlideInB::create(0.3f, InputScene::create()));
}

void GamePlayLayer::resetGame(){
	GameManager* gameManager = GameManager::getInstance();
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

	gameManager->resetGame();

	if(road){
		road->removeFromParent();
		gameManager->road = 0;
	}
	DELETE_SAFELY(road);
	road = new Road;
    road->retain();
	road->init(CCSizeMake(gameManager->roadLength, gameManager->laneWidth * 3));
	road->setAnchorPoint(ccp(0, 0.5));
	road->setPosition(10, visibleSize.height/2);
	road->start();
	addChild(road);
	gameManager->road = road;
}

void GamePlayLayer::replayButtonTouched(CCObject *sender, CCControlEvent controlEvent){
//	showAlertSaveGame();
    GameManager::getInstance()->endSaveSession();
    resetGame();
}

//void GamePlayLayer::showAlertSaveGame(){
//    int sessionDuration = atoi(sessionTimeInputField->editBox->getText());
//    char message[256] = {0};
//    if(sessionDuration != 0) {
//        sprintf(message, "Do you want to reset session with session time %d (second)?\n Data will be auto saved before reset.", sessionDuration);
//    }
//    else{
//        strcpy(message, "Do you want to reset session with no limit session time?\n Data will be auto saved before reset.");
//    }
//	HNAlertView* alertView = HNAlertView::create(message, "Cancel", "OK", 0, this);
//	alertView->show(this);
//	isShowingAlert = true;
//}

//void GamePlayLayer::alertViewButtonTouched(int index, char* inputString){
//	if(index == 1){
//        int sessionDuration = atoi(sessionTimeInputField->editBox->getText());
//        GameManager::getInstance()->sessionDuration = sessionDuration;
//        
//		if(road){
//			CCArray* vehicles = road->getVehicles();
//			GameManager* gameManager = GameManager::getInstance();
//			CCObject* it;
//			CCARRAY_FOREACH(vehicles, it){
//				Vehicle* vehicle = (Vehicle*)it;
//				VehicleInfo* vehicleInfo = (VehicleInfo*)gameManager->vehicleInfoDictionary->objectForKey(vehicle->getVehicleId());
//				if(vehicleInfo){
//					vehicleInfo->updateNumTurn(vehicle);
//				}
//			}
//			GameManager::getInstance()->endSaveSession();
//		}
//		resetGame();
//	}
//	
//    else if(index == 0){
//        GameManager::getInstance()->sessionDuration = 100000;
//    }
//	
//	isShowingAlert = false;
//}

//void GamePlayLayer::oneSecondTick(float t){
//	char timeString[64] = {0};
//	sprintf(timeString, "Time: %d", GameManager::getInstance()->gameTime);
//	timeLabel->setString(timeString);
    

//	if(GameManager::getInstance()->gameTime >= GameManager::getInstance()->sessionDuration && GameManager::getInstance()->sessionDuration > 0){
//		if(isShowingAlert == false){
//			showAlertSaveGame();
//		}
//	}
//}

void GamePlayLayer::updateTimeLabel() {
    char timeLabelString[64];
    CCString* timeString = Utils::getTimeString(GameManager::getInstance()->getGameTime());
    sprintf(timeLabelString, "Time: %s", timeString->getCString());
    timeLabel->setString(timeLabelString);
}

void GamePlayLayer::updateEndTimeLabel() {
    char timeLabelString[64];
    CCString* timeString = Utils::getTimeString(GameManager::getInstance()->inputData->getMaxStartTime());
    sprintf(timeLabelString, "End: %s", timeString->getCString());
    endTimeLabel->setString(timeLabelString);
}

void GamePlayLayer::gameTimeChangeNotification(CCObject* obj) {
    updateTimeLabel();
}